package com.david.map

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.room.Room
import com.amap.api.maps.AMap
import com.amap.api.maps.MapView
import com.amap.api.maps.MapsInitializer
import com.amap.api.maps.model.AMapGestureListener
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.maps.model.MyLocationStyle
import com.david.map.markertest.AddressInfo
import com.david.map.markertest.AppDatabase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlin.random.Random


//参考链接：https://lbs.amap.com/api/android-sdk/guide/create-project/dev-attention
class MapTestActivity : AppCompatActivity() {
    private lateinit var mapView: MapView
    private lateinit var aMap: AMap

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_map_test)

        MapsInitializer.updatePrivacyShow(this, true, true)
        MapsInitializer.updatePrivacyAgree(this, true)



        mapView = findViewById(R.id.mapview)
        mapView.apply {
            onCreate(savedInstanceState) // 此方法必须重写

            val myLocationStyle = MyLocationStyle() //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE) //定位一次，且将视角移动到地图中心点。

            myLocationStyle.interval(200000) //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。

            aMap = map
            aMap.myLocationStyle = myLocationStyle //设置定位蓝点的Style

            //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
            //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
            aMap.isMyLocationEnabled = true // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

            aMap.setAMapGestureListener(object : AMapGestureListener {
                override fun onDoubleTap(p0: Float, p1: Float) {}

                override fun onSingleTap(p0: Float, p1: Float) {}

                override fun onFling(p0: Float, p1: Float) {}

                override fun onScroll(p0: Float, p1: Float) {}

                override fun onLongPress(p0: Float, p1: Float) {}

                override fun onDown(p0: Float, p1: Float) {}

                override fun onUp(p0: Float, p1: Float) {}

                override fun onMapStable() {
                    getPointsFromScreen()
                }
            })

            //val marker = aMap.addMarker(MarkerOptions().position(LatLng(30.230934, 120.148849)).title("雷峰塔").snippet("DefaultMarker"))
            //markers.add(marker)

        }

        //findViewById<View>(R.id.)


        db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "database-name"
        ).build()

        findViewById<View>(R.id.addmarder).setOnClickListener {
            lifecycleScope.launch(Dispatchers.IO) {
                val addressDao = db?.addressDao()
                //            addressDao?.insertAddr(AddressInfo("11111", 29.910000f,120.759999f, "test address"))
                Log.e("room", "insert start...")
                var lng = 0.0
                var lat = 0.0
                val list = ArrayList<AddressInfo>()
                val markers = ArrayList<MarkerOptions>()
                for (i in 0..100) {
                    lat = getRandomLat()
                    lng = getRandomLng()
                    list.add(AddressInfo("$lat$lng", lat,lng, "test address$lat $lng"))
                    markers.add(MarkerOptions().position(LatLng(lat, lng)).title("雷峰塔").snippet("DefaultMarker"))
                }
                aMap.addMarkers(markers, false)
                addressDao?.insertAllAddr(list)
                Log.e("room", "insert finish...")
            }
        }

        getPointsFromScreen()
    }

    private val markers = ArrayList<MarkerOptions>()
    fun getPointsFromScreen() {
        lifecycleScope.launch {
            //db?.addressDao()?.getAll()?.collectLatest {
            val region = aMap.projection.visibleRegion
            if (markers.isNotEmpty()) {
                //markers.forEach {
                    //aMap.clear(it)
                //}
            }
            db?.addressDao()?.queryRangeAddress(region.farLeft.longitude, region.farLeft.latitude, region.nearRight.longitude, region.nearRight.latitude)?.collectLatest {
                //val markers = ArrayList<MarkerOptions>()
                for (i in it.indices) {
                    markers.add(MarkerOptions().position(LatLng(it[i].latitude, it[i].longitude)).title("雷峰塔").snippet("DefaultMarker"))
                }
                aMap.addMarkers(markers, false)
            }
        }
    }

    fun getRandomLat(): Double {
        //        val lngStart = 119890000 //869999
        val latStart = 29910000f  //389999
        //        val random = Random(869999)
        //        val lngValue = random.nextInt() / 1000000.0
        val latValue = (latStart+ Random.nextInt(389999)) / 1000000.0

        // fmt.Printf("lngValue is %f\n", lngValue)
        // fmt.Printf("latValue is %f", latValue)
        return latValue
    }
    fun getRandomLng (): Double {
        val lngStart = 119890000f //869999
        //        val latStart = 29910000  //389999
        //        val random = Random(389999)
        //        val lngValue = random.nextInt() / 1000000.0
        val lngValue = (lngStart+ Random.nextInt(869999)) / 1000000.0

        // fmt.Printf("lngValue is %f\n", lngValue)
        // fmt.Printf("latValue is %f", latValue)
        return lngValue
    }



    private var db: AppDatabase? = null




    override fun onDestroy() {
        super.onDestroy()
        markers.clear()
        mapView.onDestroy()
    }
}